<?php
/*
* Author: Jason ZHENG <zmj522008@hotmil.com>
* Date  : 2018/05/21
* Class : User 用户管理
*/
namespace app\index\controller;

use app\index\controller\Sms\AliYunSms;
use app\index\service\DataReturnService as DRS;
use PhpOffice\PhpSpreadsheet\Calculation\Exception;
use think\Controller;
use think\Db;
use think\Session;
use think\Request;
use app\index\common\Base;
use app\index\controller\Log\OperationLog as OL;
class User extends Controller
{ 

	public function index()
	{
		return 'User account management';
	}

	// 我的钱包记录
	public function my_wallet(Request $request)
	{
		$postData = $request->post();
	
		$days = isset($postData['days']) ? $postData['days']: null;
		if($days == 7 || $days == 30)
		{
			$startDate 	= date('Y-m-d', strtotime('-'.$days.' days'));
			$endDate   	= '2222-01-01 00:00:00';
		}else{
			$startDate 	= isset($postData['start_date']) ? $postData['start_date'] : '1700-01-01 00:00:00';
			$endDate   	= isset($postData['end_date']) ? $postData['end_date'] : '2222-01-01 00:00:00';
		}

		$page 		= isset($postData['page']) ? $postData['page'] : 1;
		$operating  = isset($postData['operating']) ? $postData['operating'] : null;

		$accountDetails = self::account_details($startDate, $endDate, $page, $operating);

		$returnData =  [
							'accountBalance' 		=> self::account_balance(),
							'accountNotBalance' 	=> self::account_not_balance(), 
							'accountDetails' 		=> [
														'count' => $accountDetails['count'],
														'list'  => $accountDetails['list']
														]
						];
		return ['code' => 666, 'msg' => 'ok', 'data' => $returnData];
	}

	// 获取账户可用余额
	public static function account_balance()
	{
		$user = Db::table('users')->where(['id' => Session::get('user.id')])->find();
		if(empty($user))
			return 0;
		else
			return $user['card_balance'];
	}

	// 获取账户不可用余额（未结算的订单总价）
	public static function account_not_balance()
	{
		$ordersUnsettled = Db::table('orders')
				->alias('o')
				->join('orders_info oi', 'o.batchcode = oi.batchcode', 'LEFT')
				->where(['o.business_id' => Session::get('user.id'), 'o.state' => 0, 'oi.is_settlement' => 0])
				->select();
		
		$notBalanceTotal = 0;
		foreach ($ordersUnsettled as $key => $order) {
			$notBalanceTotal = $notBalanceTotal + $order['price'];
		}
		return $notBalanceTotal;		
	}

	// 获取账户详情（收入和支出明细）
	// params：$startDate => 搜索开始日期， $endDate=> 搜索结束日期 ， $page=> 页数， $operating=> 收入支出（0为充值，1为消费）
	public static function account_details($startDate, $endDate, $page, $operating)
	{	

	 	$operatingType = ($operating === 0| $operating === 1) ? [$operating] : [0,1];

		$card_balance_log = Db::table('card_balance_log')
				 ->alias('cbl')
				 ->join('orders o','cbl.batchcode = o.batchcode','LEFT')
				 ->join('orders_info oi', 'cbl.batchcode = oi.batchcode', 'LEFT')
				 ->where(['cbl.user_id' => Session::get('user.id'), 'cbl.state' => 0 ])
				 ->where('cbl.createtime', '>=', $startDate )
				 ->where('cbl.createtime', '<=', $endDate )
				 ->where('cbl.operating', 'in', $operatingType)
				 ->limit(($page-1)*20,$page*20-1)
				 ->field('cbl.*, o.business_id, o.pay_code, o.payment_status, o.pay_time, oi.pay_batchode, oi.info_batchcode, oi.product_id,oi.product_name, oi.original_price, oi.price, oi.cost_price, oi.peer_price, oi.pay_reatetime,oi.other_fee')
				 ->select();

		$count = Db::table('card_balance_log')
				 ->alias('cbl')
				 ->join('orders o','cbl.batchcode = o.batchcode','LEFT')
				 ->join('orders_info oi', 'cbl.batchcode = oi.batchcode', 'LEFT')
				 ->where(['cbl.user_id' => Session::get('user.id'), 'cbl.state' => 0 ])
				 ->where('cbl.createtime', '>=', $startDate )
				 ->where('cbl.createtime', '<=', $endDate )
				 ->where('cbl.operating', 'in', $operatingType)
				 ->count();
		return ['count' => $count, 'list' => $card_balance_log];
	
	}

	/**
	 * @Notes:商户登陆
	 * @param Request $request
	 * @return array
	 * @throws \think\Exception
	 * @author: LiBaoJin
	 * @Time:2018-9-4 14:19
	 */
	public function login(Request$request) {
		$postData = $request->post();
		$rules = [
			'phone'  => ['regex'=>'/^((13[0-9])|(14[4,7])|(15[0-3,5-9])|16[6]|(17[0,3,5-8])|(18[0-9])|(19[89]))\d{8}$/','require'],
			'password'   => ['require'],
		];
		$msg = [
			'phone.regex' => '手机号规则错误',
			'phone.require'=>'手机号不能为空',
			'password.require'=>'密码不能为空',
			'password.regex'=>'密码必须包含数字与字母'
		];
		$rule = $this->validate($postData,$rules,$msg);
		if($rule !== true){
			return DRS::returnError(-1,$rule);
		}
		try{
			$user = Db::table('users')->where(['phone'=>$postData['phone']])
				->find();
			if(empty($user)){
				return DRS::returnError(-2,'该平台没有该用户!');
			}elseif($postData['password'] != $user['password']){
				return DRS::returnError(-3,'密码错误!');
			}elseif($user['state'] == 1){
				return DRS::returnError(-4,'账号异常已被禁用！！！!');
			}elseif($user['is_business'] == 0 && $user['is_staff'] == 0 && $user['shop'] == 0){
				return DRS::returnError(-5,'该用户是非商户/非门店/非员工');
			}elseif($user['is_business']==0){//高级商户
				return DRS::returnError(-6,'普通商户无法登陆');
			}else{
				$token = md5(time().$user['id']);
				$token_data = Db::table('token')->where(['user_id' => $user['id']])->select();
				if(!empty($token_data)){
					DB::table('token')->where(['user_id' => $user['id']])->delete();
				}
				DB::table('token')->insert(['token_value' => $token, 'user_id' => $user['id'], 'add_time' => date('Y-m-d H:i:s')]);
				DB::table('users')->where(['id' => $user['id']])->update([
					'last_login_time'=>date('Y-m-d H:i:s',time())
				]);
				$user_data = Db::table('users')
					->alias('u')
					->join('business b','u.id = b.business_id')
					->field('u.id,u.system_id,u.is_business,u.name,u.state,u.grade,u.agent,u.shop,u.is_staff,u.is_address,u.phone,u.card_balance,u.enjoy_currency,u.is_identity,u.createtime,u.last_login_time,b.is_auth')
					->where(['phone'=>$postData['phone'],'system_id'=>1])
					->find();
				if($user_data['is_business']==1||$user_data['is_business']==2){
					$apurview_list = db('permissions')
						->alias('p')
						->join('modules_all m','p.modules_all_id = m.id',"LEFT")
						->where('p.state',0)
						->where('m.state',0)
						->where('m.modules_title','<>','null')
						->select();
				}else{
					$apurview_list = db('permissions')
						->alias('p')
						->join('modules_all m','p.modules_all_id = m.id',"LEFT")
						->where('p.user_id',$user_data['id'])
						->where('p.state',0)
						->where('m.state',0)
						->where('m.modules_title','<>','null')
						->select();
				}
				foreach ($apurview_list as $key => $value) {
					$user_data['apurview'][$key] = [
						'path' => $value['modules_funtion'],
						'name' => $value['modules_title'],
						'component' => $value['component'],
						'meta' => explode(",",$value['remark'])
					];
				}
				OL::insert([
					'user_id'=> $user['id'],
					'module' => 'users',
					'module_id' => $user['id'],
					'operation_type' => 5,
					'operation_content' => json_encode(['users' => $user])
				]);
			}
			return DRS::returnOk(['token'=>$token,'data'=>$user_data],'登陆成功');
		}catch(Exception$e){
			return DRS::returnError(-7,$e->getMessage());
		}
	}

	/**
	 * @Notes:商户注册
	 * @param Request $request
	 * @return array
	 * @author: LiBaoJin
	 * @Time:2018-9-4 14:15
	 */
	public function register(Request$request){
      $postData = $request->post();
		$rules = [
			'avatarUrl'=>'require',
			'nickName' =>'require',
			'phone'  => ['regex'=>'/^((13[0-9])|(14[4,7])|(15[0-3,5-9])|16[6]|(17[0,3,5-8])|(18[0-9])|(19[89]))\d{8}$/','require'],
			'password'   => ['require','regex'=>'/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,60}/'],
			'phone_code'=>'require',
		];
		$msg = [
			'avatarUrl.require' => '用户头像不能为空',
			'nickName.require' => '用户昵称不能为空',
			'phone.require' => '手机号不能为空',
			'phone.regex' =>'手机号输入不正确',
			'phone_code.require' => '验证码不能为空',
			'password.require' => '密码不能为空',
			'password.regex' => '密码必须包含数字与字母'
		];
		$rule = $this->validate($postData,$rules,$msg);
		if($rule !== true){
			return DRS::returnError(-1,$rule);
		}
		$re_data = Db::table('users')->where('phone='.$postData['phone'])->find();
		if(!empty($re_data)){
			return DRS::returnError(-1,'您已经注册过');
		}
		//验证短信
		$reg = Db::table('phone_code')->where(['phone'=>$postData['phone'],'code'=>$postData['phone_code']])->find();
		if(empty($reg)){
			return DRS::returnError(-1,'验证码错误');
		}
		$postData['system_id'] = isset($postData['system_id'])?$postData['system_id']:1;
		Db::startTrans();
		try{
			$res = Db::table('users')->insertGetId([
				'phone'     => $postData['phone'],
				'password'  =>$postData['password'],
				'system_id' =>$postData['system_id'],
				'is_business' =>1,
				'createtime' => date('Y:m:d H:i:s',time()),
			]);
			if(!$res){
				return DRS::returnError(-1,'系统错误');
			}
			Db::table('business')->insertGetId([
				'business_id'     => $res,
				'business_phone'  =>$postData['phone'],
				'createtime' => date('Y:m:d H:i:s',time()),
			]);
			Db::table('user_info')->insertGetId([
				'user_id'           => $res,
				'name'              => $postData['nickName'],
				'topimageurl'       => $postData['avatarUrl'],
				'sex'               => isset($postData['gender']) ? $postData['gender'] : 3,
				'country'           => isset($postData['country']) ? $postData['country'] : null,
				'province'          => isset($postData['province']) ?  $postData['province']: null,
				'city'              => isset($postData['city']) ? $postData['city'] : null,
				'createtime' => date('Y:m:d H:i:s',time()),
			]);
			DB::commit();
           return DRS::returnOk('','OK');
		} catch(Exception $e){
			Db::rollback();
			return DRS::returnError(-1, $e->getMessage());
		}
	}

	/**
	 * @Notes:信息模板
	 * @param Request $request
	 * @return array
	 * @throws \think\Exception
	 * @author: LiBaoJin
	 * @Time:2018-9-4 14:24
	 */
	public function sms(Request$request){
		$postData = $request->post();
		//验证传过来的参数
		$rules = [
			'phone'  => ['regex'=>'/^((13[0-9])|(14[4,7])|(15[0-3,5-9])|16[6]|(17[0,3,5-8])|(18[0-9])|(19[89]))\d{8}$/','require'],
			'template' => 'require',
		];
		$msg = [
		 	'phone.regex'=>'手机号码不正确',
		 	'phone.require'=>'手机号不能为空',
		 	'template.require'=>'短信模板必须选择',
		];
		$rule = $this->validate($postData,$rules,$msg);
		if($rule !== true){
			return DRS::returnError(-1,$rule);
		}
		$code= rand(1000,9999);
		try{
			$data_code = Db::table('phone_code')->where(['phone'=>$postData['phone']])->find();
			if(empty($data_code)){
				Db::table('phone_code')->insert(['phone'=>$postData['phone'],'code'=>$code,'createtime'=>date('Y-m-d H:i:s',time())]);
			}else{
				$data = Db::table('phone_code')->where(['phone'=>$postData['phone']])->delete();
				if(!$data){
					return DRS::returnError(-1,'系统错误');
				}
				Db::table('phone_code')->insert(['phone'=>$postData['phone'],'code'=>$code,'createtime'=>date('Y-m-d H:i:s',time())]);
			}

		}catch(Exception $e){

			return DRS::returnError(-1,$e->getMessage());
		}

		$AliYunSms = new AliYunSms();
		$date = $AliYunSms->code_type($code,$postData['template'])->setRecNum($postData['phone']);
		return DRS::returnOk($date['data'],$date['msg']);
	}

	/**
	 * @Notes:忘记密码
	 * @param Request $request
	 * @return array
	 * @author: LiBaoJin
	 * @Time:2018-9-4 14:31
	 */
	public function forget_pwd(Request$request) {
		$post_data = $request->post();
		$rules = [
			'phone'  => ['regex'=>'/^((13[0-9])|(14[4,7])|(15[0-3,5-9])|16[6]|(17[0,3,5-8])|(18[0-9])|(19[89]))\d{8}$/','require'],
			'password'   => ['require','regex'=>'/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,60}/'],
			'phone_code'=>'require',
		];
		$msg = [
			'phone.regex' =>'手机号码错误',
			'phone.require' =>'手机号不能为空',
			'password.regex' =>'密码验证需要包含数字与字母',
			'password.require' =>'密码不能为空',
			'phone_code.require' =>'验证码不能为空'
		];
		$rule = $this->validate($post_data,$rules,$msg);
		if($rule !== true){
			return DRS::returnError(-1,$rule);
		}
		try{
			$phone_code =  Db::table('phone_code')->where(['phone'=>$post_data['phone']])->find();
			if(empty($phone_code)||$phone_code['code']!=$post_data['phone_code']){
				return DRS::returnError(-1,'验证码失败请重新验证');
			}
			$row = Db::table('users')->where('phone',$post_data['phone'])->setField('password',$post_data['password']);
			if($row) {
				$user = Db::table('users')->where('phone', $post_data['phone'])->find();
				OL::insert([
					'user_id' => $this->user_id,
					'module' => 'users',
					'module_id' => $this->user_id,
					'operation_type' => 2, // 修改
					'operation_content' => json_encode(['users' => $user])
				]);
				return DRS::returnOk('',true);
			}else{
				return DRS::returnError(-1,'和旧密码一致');
			}

		}catch(Exception$e){
			return DRS::returnError(-1,$e->getMessage());
		}
	}

	/**
	 * @Notes:退出登陆
	 * @param Request $request
	 * @return array
	 * @throws \think\Exception
	 * @author: LiBaoJin
	 * @Time:2018-9-4 14:32
	 */
	public function business_logout(Request$request){

		$postData = $request->post();
		$rules = [
			'token'=>'require'
		];
		$rule = $this->validate($postData,$rules);
		if($rule !== true){
			return DRS::returnError(-1,$rule);
		}
		try{
			$user = Base::getUserByTokenWithPhone($postData['token']);
			if(!isset($user['data'])){
				return DRS::returnError(-1,'退出失败');
			}
			DB::table('token')->where(['user_id' =>$user['data']['id']])->delete();

			OL::insert([
				'user_id'=> $this->user_id,
				'module' => 'users',
				'module_id' => $this->user_id,
				'operation_type' => 6, // logout
				'operation_content' => json_encode(['users' => '登出成功'])
			]);
			return DRS::returnOk('','退出成功');
		}catch(Exception$e){
			return DRS::returnError(-1,$e->getMessage());
		}
	}
}   